/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package PuriON_Chat;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextArea;

/**
 *
 * @author goajang
 */
public class PURION_Chat_Client implements Runnable{
    
    JTextArea textField;
    String path;
    BufferedReader br;
    
    public PURION_Chat_Client(String p, JTextArea tF)    
    {
        textField = tF;
        path = p;
       
        System.out.println("client setuped");
        tF.setAutoscrolls(true);
    }
    
    public void messageSend(String m)
    {
        
        System.out.println(m);
        try {
            //새로운 소켓을 하나 생성해서 [20008은 서버의 메세지받는 포트] 입력받은 문자열 m 을 넣고 보낸다.
            Socket sender = new Socket(path, 20008);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sender.getOutputStream()));
            bw.write(m);
            bw.newLine();
            bw.flush();
            
        } catch (UnknownHostException ex) {
            Logger.getLogger(PURION_Chat_Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(PURION_Chat_Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void run() {
        
        // 우선 서버의 메세지를 받는 소켓을 생성한 후 버퍼리더를 물린다.
        // br.readLine();로 한줄씩 읽음.
        
        try {

            br = new BufferedReader( new InputStreamReader(new Socket(path, 20006).getInputStream()));
            
            
        } catch (UnknownHostException ex) {
            Logger.getLogger(PURION_Chat_Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(PURION_Chat_Client.class.getName()).log(Level.SEVERE, null, ex);
        }
            
        
        while(true)
        {
        
            try {
                
                //이미 열려있는 버퍼리더에서 한줄씩 읽어와서 텍스트필드에 내용추가.
                // 사이클 하나 돌때마다 메세지 출력. 
                System.out.println("client");

                //textField.setText(textField.getText() + "\n" + br.readLine());
                textField.append("\n" + br.readLine());


            } catch (IOException ex) {
                Logger.getLogger(PURION_Chat_Client.class.getName()).log(Level.SEVERE, null, ex);
            }
                
        }
        
    }

}
